package com.bitspilani.infonet.core;

import java.util.List;

import android.location.Location;
import android.location.LocationManager;

import com.bitspilani.infonet.MainActivity;
import com.bitspilani.infonet.bo.LastKnownLocation;

public class LocationProvider {
	private static LocationManager mlocManager ;//= MainActivity.getMlocManager();

	private static LastKnownLocation lastLoc = new LastKnownLocation();

	public static LastKnownLocation getBestKnownLocation(){// this fuction will return the most accurate location after polling all the providers
		mlocManager = MainActivity.getMlocManager();
		
		if(mlocManager == null){
			System.out.println("mlocManager not initialized, returning null");
			return null;
		}
		List<String> mProviders = mlocManager.getAllProviders();
		for(int i = 0; i< mProviders.size();i++){
			Location tempLocation = mlocManager.getLastKnownLocation(mProviders.get(i));
			
			if(tempLocation == null){
				System.out.println("Null location received at LocationProvider>getBestKnownLocation for provider: "+mProviders.get(i));
				continue;
			}
			
			System.out.println("LocationLog: Provider: "+mProviders.get(i)+", accuracy: "+tempLocation.getAccuracy()+", altitude: "+tempLocation.getAltitude()
					+", latitude: "+tempLocation.getLatitude()+", longitude: "+tempLocation.getLongitude()+", speed: "+tempLocation.getSpeed());
			if(i == 0){//no last location stored, update the variable
				lastLoc.setAccuracy(tempLocation.getAccuracy());//accuracy in meters, its radius in meters
				//lesser the accuracy value, more accurate the location will be
				lastLoc.setAltitude(tempLocation.getAltitude());
				lastLoc.setLattitide(tempLocation.getLatitude());
				lastLoc.setLongitude(tempLocation.getLongitude());
				lastLoc.setSpeed(tempLocation.getSpeed());//speed in meters per second
				System.out.println("LocationLog: Provider: DEFAULT SET"+mProviders.get(i)+", accuracy: "+tempLocation.getAccuracy());

			}else{
				if(lastLoc.getAccuracy() > tempLocation.getAccuracy()){//implies lastLoc.getAccuracy() is lesser accurate so update it
					lastLoc.setAccuracy(tempLocation.getAccuracy());//accuracy in meters, its radius in meters
					//lesser the accuracy value, more accurate the location will be
					lastLoc.setAltitude(tempLocation.getAltitude());
					lastLoc.setLattitide(tempLocation.getLatitude());
					lastLoc.setLongitude(tempLocation.getLongitude());
					lastLoc.setSpeed(tempLocation.getSpeed());//speed in meters per second
					System.out.println("LocationLog: Provider: UPDATED LOCATION FOR ACCURACY"+mProviders.get(i)+", accuracy: "+tempLocation.getAccuracy());
				}
			}

		}
		return lastLoc;
	}
}
